package com.manor.paradise.util

import android.graphics.*
import androidx.annotation.NonNull
import com.bumptech.glide.load.Key
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation
import com.orhanobut.logger.Logger
import java.security.MessageDigest
import kotlin.math.roundToInt

/**
 *
 */
class GyroscopeTransform(private val mWidgetWidth :Int, private val mWidgetHeight :Int) : BitmapTransformation() {
    private var mTargetWidth :Int = 0
    private var mTargetHeight :Int = 0
    private val ID = "com.manor.paradise.util.GyroscopeTransform"
    private val ID_BYTES: ByteArray = ID.toByteArray(Key.CHARSET)

    override fun transform(pool: BitmapPool, toTransform: Bitmap, outWidth: Int, outHeight: Int): Bitmap {
        if (toTransform.width == 0 || toTransform.height == 0) {
            return toTransform
        }
        mTargetWidth = toTransform.width
        mTargetHeight = toTransform.height
        val ratio: Double = mTargetWidth.toDouble() / mTargetHeight.toDouble() //图片的宽高比
        val distance: Int
        if (mWidgetHeight <= mWidgetWidth) {
            distance = mWidgetHeight / 8
            mTargetWidth = mWidgetWidth + 2 * distance
            mTargetHeight = (mTargetWidth / ratio).roundToInt()
        } else {
            distance = mWidgetWidth / 8
            mTargetHeight = mWidgetHeight + 2 * distance
            mTargetWidth = (mTargetHeight * ratio).roundToInt()
        }
        val desiredWidth = mTargetWidth
        val desiredHeight = mTargetHeight
        Logger.e("GyroscopeTransform desiredWidth = $desiredWidth , desiredHeight = $desiredHeight")
        return  Bitmap.createScaledBitmap(toTransform, desiredWidth, desiredHeight,true);
    }

    private fun setCanvasBitmapDensity(toTransform: Bitmap, canvasBitmap: Bitmap) {
        canvasBitmap.density = toTransform.density
    }

    @NonNull
    private fun getNonNullConfig(@NonNull bitmap: Bitmap): Bitmap.Config? {
        return if (bitmap.config != null) bitmap.config else Bitmap.Config.ARGB_8888
    }

    override fun equals(other: Any?): Boolean {
        return other is GyroscopeTransform
    }

    override fun hashCode(): Int {
        return ID.hashCode()
    }

    override fun updateDiskCacheKey(messageDigest: MessageDigest) {
        messageDigest.update(ID_BYTES)
    }

}


